<?php

declare(strict_types=1);

namespace app\xapply\controller;

use app\xapply\middleware\Auth;
use app\xapply\Xapply;
use think\facade\Filesystem;
use think\facade\Db;

class Upload extends Xapply
{

    protected $middleware = [Auth::class];

    /**
     * 头像上传
     * url: http://域名/xapply/upload
     * doc: http://lutui.net/doc/app/profile-avatar.html
     */
    public function index()
    {
        
        $file = request()->file('file');
        $dataPath = date('Ym');
        $md5 = $file->hash('md5');
        $filename = Filesystem::disk('public')->putFile($dataPath, $file, function () use ($md5) {
            return set_salt(5).'_'.$md5;
        });
        if ($filename) {
            $path = get_config('filesystem.disks.public.url');
            $url = $path . '/' . $filename;
            Db::name('Admin')->where(['id' => XAPPLY_UID])->strict(false)->field(true)->update([
                'thumb' => $url
            ]);
            return json(['error' => '', 'url' => request()->domain().$url]);
        }
        return json(['error' => '上传失败，请重试']);
    }
}
